package studentbooking.applications;
 
import javafx.scene.shape.Circle;
import studentbooking.db.DBHelper;
import studentbooking.bean.StudentEntity;
import studentbooking.bean.TicketInfoEntity;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.effect.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.Stop;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import utils.MayiktJdbcUtils;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import static javafx.geometry.Pos.CENTER;
import static javafx.geometry.Pos.CENTER_RIGHT;

/**
 * Created by leiYang on 2016/11/27.
 */
 
public class SelectTicket extends Application {


    StudentEntity studentEntity ;
    TableView tableView = new TableView();
    String mStart = "出发地";
    String mEnd = "目的地";

    Label label = new Label();

    ObservableList<TicketInfoEntity> data1 = FXCollections.observableArrayList();


    public static void main(String[] args) {
        launch(SelectTicket.class, args);
    }

    public SelectTicket(StudentEntity studentEntity) {
        this.studentEntity = studentEntity;
    }

    @Override
    public void start(Stage stage) throws IOException {

        BorderPane border = new BorderPane();
        HBox hbox = addHBox();

        border.setTop(hbox);
        border.setLeft(addAnchorPane(addGridPane()));

        addStackPane(hbox);  

      border.setCenter(addCenterPane());

        Scene scene = new Scene(border);
        scene.getStylesheets().add("studentbooking/css/button.css");
        stage.setScene(scene);
        stage.setTitle("学生火车票订票系统");
        stage.show();
    }
    Button submit = new Button("预定");
    Button cancel = new Button("退票");

    private GridPane addCenterPane() {
        GridPane  centerGridPane = new GridPane();
        centerGridPane.setAlignment(CENTER);
        centerGridPane.setHgap(10.0);
        centerGridPane.setVgap(10.0);
        centerGridPane.setPadding(new Insets(10.0,10.0,10.0,10.0));
        label = new Label(mStart+" ——> "+mEnd);
        label.getStyleClass().add("label1");
        centerGridPane.add(label,0,0);

        submit.getStyleClass().add("button3");
        centerGridPane.add(submit,1,0);
        submit.setVisible(false);

        cancel.getStyleClass().add("button3");
        centerGridPane.add(cancel,2,0);
        cancel.setVisible(false);

        tableView = new TableView();
        tableView.setId("tableView");
        tableView.setEditable(true);
        tableView.setPrefHeight(500);

        TableColumn checkBoxColumn = new TableColumn("勾选");   //选中框
        checkBoxColumn.setCellFactory(CheckBoxTableCell.forTableColumn(checkBoxColumn));
        checkBoxColumn.setCellValueFactory(new PropertyValueFactory<>("isSelected"));

        checkBoxColumn.setEditable(true);


        TableColumn trainNameCol = new TableColumn("车次");
        trainNameCol.setCellValueFactory(new PropertyValueFactory<>("trainName"));
        TableColumn startNameCol = new TableColumn("起点");
        startNameCol.setCellValueFactory(new PropertyValueFactory<>("startPlace"));
        TableColumn endNameCol = new TableColumn("终点");
        endNameCol.setCellValueFactory(new PropertyValueFactory<>("endPlace"));
        TableColumn remainTicketsCol = new TableColumn("库存");
        remainTicketsCol.setCellValueFactory(new PropertyValueFactory<>("remainTickets"));
        TableColumn ticketTypeCol = new TableColumn("车票类型");
        ticketTypeCol.setCellValueFactory(new PropertyValueFactory<>("ticketType"));
        TableColumn startTimeCol = new TableColumn("发车时间");
        startTimeCol.setCellValueFactory(new PropertyValueFactory<>("startTime"));
        TableColumn endTimeCol = new TableColumn("到达时间");
        endTimeCol.setCellValueFactory(new PropertyValueFactory<>("endTime"));
        TableColumn fareCol = new TableColumn("票价");
        fareCol.setCellValueFactory(new PropertyValueFactory<>("fare"));


        tableView.getColumns().addAll(checkBoxColumn,trainNameCol,startNameCol,endNameCol,remainTicketsCol,ticketTypeCol,startTimeCol,endTimeCol,fareCol);

        centerGridPane.add(tableView,0,1,3,1);

        submit.setOnMouseClicked((MouseEvent t)->{

            ObservableList<TicketInfoEntity> mResult = tableView.getItems();
            System.out.println("mResult.size()" + mResult.size());
            for (int i = 0; i < mResult.size(); i++) {
                Boolean aBoolean = mResult.get(i).getIsIsSelected();
                if (aBoolean){

                    System.out.println("结果集合："+"被点击了"+mResult.get(i).getStartTime());
                    mResult.get(i).setRemainTickets(mResult.get(i).getRemainTickets()-1);
//                    saveInfo.add(mResult.get(i));
                    saveIntoSQL(mResult.get(i));

                } else {
                    System.out.println("结果集合："+"没有点击"+mResult.get(i).getStartTime());
                }
            }
        });

        cancel.setOnMouseClicked((MouseEvent t)->{
            ObservableList<TicketInfoEntity> mResult = tableView.getItems();
            ArrayList<Boolean> mResultCopy = new ArrayList<Boolean>();
            int size = mResult.size();
            for (int i = 0; i < size; i++) {
                mResultCopy.add(mResult.get(i).getIsIsSelected());
            }
            System.out.println("mResult.size()" + mResult.size());
            for (int i = 0; i < size; i++) {
                if (mResultCopy.get(i)){
                    System.out.println("结果集合："+"被点击了"+mResult.get(i).getStartTime());
                    mResult.get(i).setRemainTickets(mResult.get(i).getRemainTickets()+1);
                    removeFromOrders(mResult.get(i));
//                    saveInfo.remove(i);
                    data1.remove(i);
                }
            }
        });

        return centerGridPane;
    }

    private void removeFromOrders(TicketInfoEntity ticketInfoEntity) {
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        int result=0;
        try {
            connection = MayiktJdbcUtils.getConnection();
            preparedStatement=connection.prepareStatement("SELECT * FROM Orders WHERE trainName=? and startTime=? and endTime=? ");
            preparedStatement.setString(1,ticketInfoEntity.getTrainName());
            preparedStatement.setString(2,ticketInfoEntity.getStartTime());
            preparedStatement.setString(3,ticketInfoEntity.getEndTime());
            resultSet=preparedStatement.executeQuery();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        String strNum = "201612151212";
        try {
            if (resultSet.next()){
                strNum = resultSet.getString("orderNum");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        String sqlstr = "DELETE FROM Orders WHERE orderNum = '"+strNum+"'";
        try {
            preparedStatement=connection.prepareStatement("delete from Orders where orderNum=?");
            preparedStatement.setString(1,strNum);
            result=preparedStatement.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
//        try {
//            preparedStatement=connection.prepareStatement("UPDATE Orders SET remainTickets =? where trainName=? and startPlace=? and endPlace=?");
//            preparedStatement.setInt(1,ticketInfoEntity.getRemainTickets());
//            preparedStatement.setString(2,ticketInfoEntity.getTrainName());
//            preparedStatement.setString(3,ticketInfoEntity.getStartPlace());
//            preparedStatement.setString(3,ticketInfoEntity.getEndPlace());
//            result=preparedStatement.executeUpdate();
//        } catch (SQLException throwables) {
//            throwables.printStackTrace();
//        }



    }

    ArrayList<TicketInfoEntity> saveInfo = new ArrayList<>();
    private int orderNum = 0;

    private void saveIntoSQL(TicketInfoEntity ticketInfoEntity) {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(date);
        orderNum++;
        Date date1 = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String time1 = simpleDateFormat.format(date1);

        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        int result=0;

        try {
            connection=MayiktJdbcUtils.getConnection();
            preparedStatement=connection.prepareStatement("INSERT INTO Orders VALUES(?,?,?,?,?,?,?,?,?,?,?,?)");
            preparedStatement.setString(1,time1);
            preparedStatement.setString(2,studentEntity.getName());
            preparedStatement.setString(3,time);
            preparedStatement.setString(4,"否");
            preparedStatement.setString(5,ticketInfoEntity.getTrainName());
            preparedStatement.setString(6,ticketInfoEntity.getStartPlace());
            preparedStatement.setString(7,ticketInfoEntity.getEndPlace());
            preparedStatement.setString(8,ticketInfoEntity.getStartTime());
            preparedStatement.setString(9,ticketInfoEntity.getEndTime());
            preparedStatement.setString(10,ticketInfoEntity.getTicketType());
            preparedStatement.setInt(11,ticketInfoEntity.getRemainTickets());
            preparedStatement.setFloat(12,ticketInfoEntity.getFare());
            result=preparedStatement.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }


    }


    private HBox addHBox() {
 
        HBox hbox = new HBox();
        hbox.setPadding(new Insets(10, 20, 35, 20));
        hbox.setSpacing(10);   // Gap between nodes
        hbox.setStyle("-fx-background-color: #f0f0f0;");

//        Text text = new Text("  学生火车票订票系统");
//        text.setFont(Font.font("Verdana", FontWeight.BOLD, 30));
//        text.setFill(Color.valueOf("#0795F4"));
//
        Text t = new Text();
        t.setX(10.0f);
        t.setY(50.0f);
        t.setCache(true);
        t.setText("学生火车票订票系统");
//        t.setFill(Color.RED);
        t.setFill(Color.valueOf("#0795F4"));
        t.setFont(Font.font( 35));

        Reflection r = new Reflection();
        r.setFraction(0.7f);

        t.setEffect(r);

//        t.setTranslateY(400);

        hbox.getChildren().add(t);


        return hbox;
    }


    private void addStackPane(HBox hb) {
 
        StackPane stack = new StackPane();
        Circle helpIcon = new Circle(14.5);
        helpIcon.setFill(new LinearGradient(0,0,0,1, true, CycleMethod.NO_CYCLE,
            new Stop[]{
            new Stop(0,Color.web("#0078D7")),
            new Stop(0.5, Color.web("#0078D7")),
            new Stop(1,Color.web("#0078D7")),}));
        helpIcon.setStroke(Color.web("#0078D7"));


        Text helpText = new Text("?");
        helpText.setFont(Font.font("Verdana", FontWeight.BOLD, 15));
        helpText.setFill(Color.WHITE);
        helpText.setStroke(Color.web("#7080A0")); 
        
        stack.getChildren().addAll(helpIcon, helpText);
        stack.setAlignment(CENTER_RIGHT);
        StackPane.setMargin(helpText, new Insets(0, 10, 0, 0));
        
        hb.getChildren().add(stack);
        HBox.setHgrow(stack, Priority.ALWAYS);

        final Boolean[] flag = {false};
        stack.setOnMouseClicked((MouseEvent t)->{
            if (!flag[0]){
                helpText.setText("制作人：北辰星      !");
                flag[0] = true;
            } else {
                helpText.setText("?");
                flag[0] = false;
            }
        });
                
    }
 

    private GridPane addGridPane() {
 
        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(10, 20, 0, 10));

        Text category = new Text("用户："+studentEntity.getName());
        category.setFont(Font.font( 20));
        grid.setMargin(category,new Insets(10,0,0,0));
        grid.add(category, 1,0);

        Text school = new Text("学校："+studentEntity.getUniversity());
        school.setFont(Font.font(20));
        grid.add(school, 1, 1);


        TextField startCity = new TextField();
        startCity.setPromptText("出发城市");
        grid.setMargin(startCity,new Insets(10,0,0,0));
        GridPane.setConstraints(startCity, 1, 2);
        grid.getChildren().add(startCity);

        TextField endCity = new TextField();
        endCity.setPromptText("到达城市");
        grid.setMargin(endCity,new Insets(5,0,10,0));
        GridPane.setConstraints(endCity, 1, 3);
        grid.getChildren().add(endCity);


        Text tip1 = new Text("您可以选择");
        tip1.setFont(Font.font("Arial", 12));
        tip1.setFill(Color.web("#A2A2A2"));
        grid.add(tip1,1,4);

        Button searchTicket = new Button();
        searchTicket.setText("搜索车票");
        searchTicket.getStyleClass().add("button1");
        grid.setMargin(searchTicket,new Insets(0,0,10,0));
        grid.add(searchTicket,1,5);

        Text tip2 = new Text("或者是");
        tip2.setFont(Font.font("Arial", FontWeight.BOLD, 12));
        tip2.setFill(Color.web("#A2A2A2"));
        grid.add(tip2,1,6);

        Button searchOrders = new Button();
        searchOrders.setText("查看订单");
        searchOrders.getStyleClass().add("button2");
        grid.add(searchOrders,1,7);



        searchTicket.setOnMouseClicked((MouseEvent t)->{

            submit.setVisible(true);
            cancel.setVisible(false);

            data1.clear();
            String mStartCity = startCity.getText();
            String mEndPlace = endCity.getText();

            if (mStartCity == null || mStartCity.equals(" ") || mStartCity.equals("")){
                mStartCity = mStart;
            }else{
                System.out.println("mStartPlace : "+mStartCity );
            }
            if (mEndPlace == null || mEndPlace.equals(" ") || mEndPlace.equals("")){
                mEndPlace = mEnd;
            }
            label.setText(mStartCity+" ——> "+mEndPlace);
//            DBHelper dbHelper = new DBHelper();
//            String sqlstr = "SELECT * FROM Train_Info WHERE station_name = '"+mStartCity+"'";
//            dbHelper.executeSQL(sqlstr);
//            ResultSet resultSet = dbHelper.getResultSet();

            Connection connection3=null;
            PreparedStatement preparedStatement3=null;
            ResultSet resultSet3=null;
            int result=0;

            try {
                connection3=MayiktJdbcUtils.getConnection();
                preparedStatement3=connection3.prepareStatement("SELECT * FROM ticketinfo WHERE startPlace=? ");
                preparedStatement3.setString(1,mStartCity);
                resultSet3=preparedStatement3.executeQuery();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            try {
                while (resultSet3.next()){
                    String mTrainName = resultSet3.getString("trainName");
                    int num = resultSet3.getInt("remainTickets");
                    String mStartTime = resultSet3.getString("startTime");
                    String mEndTime = resultSet3.getString("endTime");
                    float mStartFare = resultSet3.getFloat("fare");

                    Connection connection4=null;
                    PreparedStatement preparedStatement4=null;
                    ResultSet resultSet4=null;
                    connection4=MayiktJdbcUtils.getConnection();
                    preparedStatement4=connection4.prepareStatement("SELECT * FROM Train_Info WHERE stationName =? and trainName=?");
                    preparedStatement4.setString(1,mStartCity);
                    preparedStatement4.setString(2,mTrainName);
                    resultSet4=preparedStatement4.executeQuery();
//                    String sqlstr1 = "SELECT * FROM Train_Info WHERE station_name = '"+mEndPlace+"' AND train_name = '"+mTrainName+"'";
//                    DBHelper dbHelper1 = new DBHelper();
//                    dbHelper1.executeSQL(sqlstr1);
//                    ResultSet resultSet1 = dbHelper1.getResultSet();
                    while(resultSet4.next()){
                        int endNum = resultSet4.getInt("num");
                        if (endNum > num) {
                            String ticketType;
                            if (studentEntity.getAddress().contains(mEndPlace)){
                                ticketType = "学生票";
                            } else{
                                ticketType = "成人票";
                            }
                            float mEndFare = resultSet4.getFloat("fare");


                            String trainName = resultSet4.getString("trainName");

                            Connection connection5=null;
                            PreparedStatement preparedStatement5=null;
                            ResultSet resultSet5=null;
                            int result5=0;
                            connection5=MayiktJdbcUtils.getConnection();
                            preparedStatement5=connection5.prepareStatement("select * from Orders where trainName=? and startPlace=? and endPlace=?");
                            preparedStatement5.setString(1,trainName);
                            preparedStatement5.setString(2,mStartCity);
                            preparedStatement5.setString(3,mEndPlace);
                            resultSet5=preparedStatement5.executeQuery();

                            int remainTickets = 300;
                            while (resultSet5.next()){
                                int remain = resultSet5.getInt("remainTickets");
                                if (remainTickets > remain){
                                    remainTickets = remain;
                                }
                            }

                            System.out.println(mStartCity+"-->"+mEndPlace);
                            TicketInfoEntity ticketInfoEntity = new TicketInfoEntity();
                            ticketInfoEntity.setTrainName(trainName);
                            ticketInfoEntity.setStartPlace(mStartCity);
                            ticketInfoEntity.setEndPlace(mEndPlace);
                            ticketInfoEntity.setStartTime(mStartTime);
                            ticketInfoEntity.setEndTime(mEndTime);
                            ticketInfoEntity.setTicketType(ticketType);
                            ticketInfoEntity.setFare(mEndFare);
                            ticketInfoEntity.setRemainTickets(remainTickets);
                            ticketInfoEntity.setIsSelected(false);

                            data1.add(ticketInfoEntity);
                            tableView.setItems(data1);
                            System.out.println("data1.size: "+data1.size()+data1.get(0).getStartTime());
//                            createTableViewRow(ticketInfoEntity);

                        }
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        });

        final Boolean[] firstTime = {true};

        searchOrders.setOnMouseClicked((MouseEvent t)->{
            data1.clear();
//            if (firstTime[0]){
//                String sqlstr = "SELECT * FROM Orders WHERE name = '"+studentEntity.getName()+"'";
//                DBHelper dbHelper = new DBHelper();
//                dbHelper.executeSQL(sqlstr);
//                ResultSet resultSet = dbHelper.getResultSet();

            Connection connection2=null;
            PreparedStatement preparedStatement2=null;
            ResultSet resultSet2=null;
            int result2=0;
            try {
                connection2=MayiktJdbcUtils.getConnection();
                preparedStatement2=connection2.prepareStatement("SELECT * FROM Orders WHERE name =?");
                preparedStatement2.setString(1,studentEntity.getName());
                resultSet2=preparedStatement2.executeQuery();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            try {
                    while (resultSet2.next()){
                        TicketInfoEntity ticketInfoEntity = new TicketInfoEntity();
                        ticketInfoEntity.setRemainTickets(resultSet2.getInt("remainTickets"));
                        ticketInfoEntity.setIsSelected(false);
                        ticketInfoEntity.setFare(resultSet2.getFloat("fare"));
                        ticketInfoEntity.setEndPlace(resultSet2.getString("endPlace"));
                        ticketInfoEntity.setEndTime(resultSet2.getString("endTime"));
                        ticketInfoEntity.setStartPlace(resultSet2.getString("startPlace"));
                        ticketInfoEntity.setStartTime(resultSet2.getString("startTime"));
                        ticketInfoEntity.setTicketType(resultSet2.getString("ticketType"));
                        ticketInfoEntity.setTrainName(resultSet2.getString("trainName"));
//                        saveInfo.add(ticketInfoEntity);

                        data1.add(ticketInfoEntity);
                        tableView.setItems(data1);
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
//            }else{
//                for (int i = 0; i < saveInfo.size(); i++) {
//                    data1.add(saveInfo.get(i));
//                }
//            }
//            firstTime[0] = false;

            submit.setVisible(false);
            cancel.setVisible(true);
        });
        return grid;
    }


    private AnchorPane addAnchorPane(GridPane grid) {
 
        AnchorPane anchorpane = new AnchorPane();

        HBox hb = new HBox();
        hb.setPadding(new Insets(0, 10, 10, 10));
        hb.setSpacing(10);

        anchorpane.getChildren().addAll(grid,hb);
        AnchorPane.setBottomAnchor(hb, 8.0);
        AnchorPane.setRightAnchor(hb, 5.0);
        AnchorPane.setTopAnchor(grid, 10.0);
 
        return anchorpane;
    }
}